package com.sunny.ihealth.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.sunny.ihealth.R;
import com.sunny.ihealth.entity.bmob.Post;
import com.sunny.ihealth.entity.bmob.State;
import com.sunny.ihealth.entity.bmob.UserInfo;
import com.sunny.ihealth.ui.activity.PhotoViewActivity;
import com.sunny.ihealth.utils.FastBlurUtils;
import com.sunny.ihealth.utils.TimeUtils;
import com.sunny.ninepictureview.NinePictureView;

import java.util.List;
import java.util.Locale;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 帖子详细信息的adapter
 * Created by Sunny  An on 2016/6/3.
 */
public class ProfileAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener {

    /**
     * header所在的位置
     */
    public static final int POSITION_HEADER = -1;
    private static final int TYPE_HEADER = 0;
    private static final int TYPE_NORMAL = 1;

    private Context context;
    //显示在header的UserInfo信息
    private UserInfo userInfo;
    private List<Post> data;
    private LayoutInflater inflater;

    private OnViewClickListener listener;

    public ProfileAdapter(Context context, UserInfo userInfo, List<Post> data) {
        this.context = context;
        this.userInfo = userInfo;
        this.data = data;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_HEADER) {
            return new HeaderHolder(inflater.inflate(R.layout.item_profile_header, parent, false));
        } else {
            return new ItemHolder(inflater.inflate(R.layout.item_post, parent, false));
        }
    }

    @Override
    public int getItemViewType(int position) {
        return position == 0 ? TYPE_HEADER : TYPE_NORMAL;
    }

    @Override
    public int getItemCount() {
        return data.size() + 1;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (getItemViewType(position) == TYPE_HEADER) { //header

            final HeaderHolder headerHolder = (HeaderHolder) holder;

            //设置头像和虚化背景
            if (userInfo.hasHead()) {
                Picasso
                        .with(context)
                        .load(userInfo.getHeadFile().getUrl())
                        .into(headerHolder.ivHead, new Callback() {
                            @Override
                            public void onSuccess() {
                                FastBlurUtils.setBlurBackground(headerHolder.ivBackground, ((BitmapDrawable) headerHolder.ivHead.getDrawable()).getBitmap(), false);
                            }

                            @Override
                            public void onError() {

                            }
                        });
            }
            headerHolder.tvName.setText(userInfo.getNickname());
            headerHolder.tvSignature.setText(userInfo.getSignature());
            headerHolder.ivGender.setImageResource(userInfo.getGender() == UserInfo.GENDER_MALE ? R.drawable.ic_boy : R.drawable.ic_girl);
            headerHolder.tvFansNumber.setText(userInfo.getFansNumber() + "");
            headerHolder.tvFriendsNumber.setText(userInfo.getFriendNumber() + "");
            if (userInfo.getPostsNumber() != null) {
                headerHolder.tvPostsNumber.setText(userInfo.getPostsNumber() + "");
            } else {
                headerHolder.tvPostsNumber.setText("0");
            }

            int state = userInfo.isFriend();
            if (state == State.STATE_BOTH_FRIEND) {
                headerHolder.tvAddFriend.setText("互相关注");
                headerHolder.tvAddFriend.setTextColor(context.getResources().getColor(R.color.lightGray));
            } else if (state == State.STATE_ADD) {
                headerHolder.tvAddFriend.setText("已关注");
                headerHolder.tvAddFriend.setTextColor(context.getResources().getColor(R.color.lightGray));
            } else {
                headerHolder.tvAddFriend.setText("+关注");
                headerHolder.tvAddFriend.setTextColor(context.getResources().getColor(R.color.white));
            }

            headerHolder.tvAddFriend.setOnClickListener(this);
            headerHolder.llPosts.setOnClickListener(this);
            headerHolder.llFriends.setOnClickListener(this);
            headerHolder.llFans.setOnClickListener(this);

            headerHolder.setTag(position);

        } else { //item
            ItemHolder itemHolder = (ItemHolder) holder;
            position = position - 1;
            final Post post = data.get(position);

            if (post.getAuthor().hasHead()) {
                Picasso.with(context).load(post.getAuthor().getHeadFile().getUrl()).into(itemHolder.ivHead);
            }
            itemHolder.tvAuthor.setText(post.getAuthor().getNickname());
            itemHolder.tvTime.setText(TimeUtils.getFriendlyTime(post.getCreatedAt()));
            itemHolder.tvContent.setText(post.getContent());
            if (TextUtils.isEmpty(post.getContent())) {
                itemHolder.tvContent.setVisibility(View.GONE);
            } else {
                itemHolder.tvContent.setVisibility(View.VISIBLE);
            }

            //NinePictureView
            if (post.getPictures() != null && post.getPictures().size() != 0) {
                itemHolder.ninePictureView.setVisibility(View.VISIBLE);
                PostNinePicAdapter adapter = new PostNinePicAdapter(context, post.getPictures());
                itemHolder.ninePictureView.setAdapter(adapter);
            } else {
                itemHolder.ninePictureView.setVisibility(View.GONE);
            }

            String likeStr;
            if (post.isLiked()) {
                likeStr = String.format(Locale.getDefault(), "已赞(%d)", post.getLikeNumber());
            } else {
                likeStr = String.format(Locale.getDefault(), "赞(%d)", post.getLikeNumber());
            }
            itemHolder.btnLike.setText(likeStr);

            String commentStr = String.format(Locale.getDefault(), "评论(%d)", post.getCommentNumber());
            itemHolder.btnComment.setText(commentStr);

            itemHolder.tvAddFriend.setVisibility(View.GONE);

            itemHolder.btnLike.setOnClickListener(this);
            itemHolder.btnComment.setOnClickListener(this);
            itemHolder.llItem.setOnClickListener(this);
            itemHolder.ninePictureView.setOnItemClickListener(new NinePictureView.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    Intent intent = new Intent(context, PhotoViewActivity.class);
                    intent.putExtra("imgs", post.getListPictures());
                    intent.putExtra("position", position);
                    context.startActivity(intent);
                }
            });
            itemHolder.setTag(position);
        }
    }

    public OnViewClickListener getListener() {
        return listener;
    }

    /**
     * 如点击的Header，position == POSITION_HEADER
     */
    public void setListener(OnViewClickListener listener) {
        this.listener = listener;
    }

    @Override
    public void onClick(View v) {
        if (listener == null) {
            return;
        }
        int position = (int) v.getTag();
        listener.onViewClick(v.getId(), getItemViewType(position) == TYPE_HEADER ? POSITION_HEADER : position - 1);
    }


    /**
     * 设置添加好友
     *
     * @param isFriend 是否是好友
     */
    public void setIsFriend(int isFriend) {
        userInfo.setIsFriend(isFriend);
        if (isFriend == State.STATE_BOTH_FRIEND || isFriend == State.STATE_ADD) {
            userInfo.setFansNumber(userInfo.getFansNumber() + 1);
        } else {
            userInfo.setFansNumber(userInfo.getFansNumber() - 1);
        }
        notifyItemChanged(0, R.id.tv_profileHeader_fansNumber);
    }

    static class ItemHolder extends RecyclerView.ViewHolder {
        LinearLayout llItem;
        CircleImageView ivHead;
        TextView tvAuthor, tvTime, tvContent;
        NinePictureView ninePictureView;
        Button btnLike, btnComment;
        TextView tvAddFriend;

        public ItemHolder(View v) {
            super(v);
            llItem = (LinearLayout) v.findViewById(R.id.ll_post_item);
            ivHead = (CircleImageView) v.findViewById(R.id.image_post_head);
            tvAuthor = (TextView) v.findViewById(R.id.tv_post_author);
            tvTime = (TextView) v.findViewById(R.id.tv_post_time);
            tvContent = (TextView) v.findViewById(R.id.tv_post_content);
            ninePictureView = (NinePictureView) v.findViewById(R.id.ninePicView_post);
            btnLike = (Button) v.findViewById(R.id.btn_post_like);
            btnComment = (Button) v.findViewById(R.id.btn_post_comment);
            tvAddFriend = (TextView) v.findViewById(R.id.tv_post_addFriend);
        }

        public void setTag(Object tag) {
            llItem.setTag(tag);
            btnComment.setTag(tag);
            btnLike.setTag(tag);
            tvAddFriend.setTag(tag);
            ivHead.setTag(tag);
            tvAuthor.setTag(tag);
        }

    }


    static class HeaderHolder extends RecyclerView.ViewHolder {
        ImageView ivBackground;
        CircleImageView ivHead;
        ImageView ivGender;
        TextView tvName, tvSignature, tvAddFriend;
        LinearLayout llPosts, llFriends, llFans;
        TextView tvPostsNumber, tvFriendsNumber, tvFansNumber;

        public HeaderHolder(View v) {
            super(v);
            ivBackground = (ImageView) v.findViewById(R.id.image_profileHeader_background);
            ivHead = (CircleImageView) v.findViewById(R.id.image_profileHeader_head);
            ivGender = (ImageView) v.findViewById(R.id.image_profileHeader_gender);
            tvName = (TextView) v.findViewById(R.id.tv_profileHeader_name);
            tvSignature = (TextView) v.findViewById(R.id.tv_profileHeader_signature);
            tvAddFriend = (TextView) v.findViewById(R.id.tv_profileHeader_addFriend);
            llPosts = (LinearLayout) v.findViewById(R.id.ll_profileHeader_postNumber);
            llFriends = (LinearLayout) v.findViewById(R.id.ll_profileHeader_friendsNumber);
            llFans = (LinearLayout) v.findViewById(R.id.ll_profileHeader_fansNumber);
            tvPostsNumber = (TextView) v.findViewById(R.id.tv_profileHeader_postNumber);
            tvFriendsNumber = (TextView) v.findViewById(R.id.tv_profileHeader_friendsNumber);
            tvFansNumber = (TextView) v.findViewById(R.id.tv_profileHeader_fansNumber);
        }

        public void setTag(Object tag) {
            tvAddFriend.setTag(tag);
            llPosts.setTag(tag);
            llFriends.setTag(tag);
            llFans.setTag(tag);
        }
    }

}
